<template>

<div class="translation" curPageName="sfsadf234245422222">


    <div class="merak-card merak-container-has-search" v-waterMarker>
        <!-- 搜索模块儿 -->
        <div>
            <serachBar custom_class="myclass" 
                    :close-plan="true"
                    :close-advanced="true"
                    :placeholder='$t("manage_set.title")' :search_val=search_val
                    @search-event="searchFn">
                        <template #footer>
                            <!-- // 权限03 -->
                        </template>
                    </serachBar>
        
        </div>
        <div class="merak-table-wrapper">
            <MerakXTable ref="tableRef" :columns-by-store="JSON.parse(JSON.stringify(state.columns))"
                        :query-columns="handleQueryColumns" :query-data="handleQueryData" :params="state.params"
                    
                        :column-type="columnTypeAuth"
                        :batches="[]"
                        :batch-click="handleBatchClick">
                        <template #handler="{ row }">
                            <div>
                                <!-- // 权限04 -->
                                <el-button type="primary" link  v-auth="{'authArr':authArr,'key':'edit'}"   @click="saveEdit(row)"> {{$t("manage_set.edit_manage_set")}} </el-button>
                            </div>
                        </template>

                        <template #color="{ row }">
            
                            <el-tag :color="row.color" style="margin-right: 8px" size="small" />
                        </template>


                        

                    </MerakXTable>
        </div>
    </div>


    <el-drawer modal-class="merak_modal manage_drawer"  v-model="drawerTranslation" direction="rtl" size="30%">
            
            <template #header>
                <div class="merak_modal_title">{{translationTitle}}</div>
            </template>
        
            <div class="form-box">
                <div  >
                    <el-form :model="setForm" ref="setRef" :rules="translationRules"
                        label-position="top">

                        <el-form-item :label='$t("manage_set.title")' prop="title">
                                    <el-input class="qf_input" v-model="setForm.title" />
                                </el-form-item>
                                <el-form-item :label='$t("manage_set.title_ru")' prop="title_ru">
                                    <el-input class="qf_input" v-model="setForm.title_ru" />
                                </el-form-item>

                        
                                <el-form-item :label='$t("manage_set.remarks")' >
                                    <el-input type="textarea" rows="4" class="qf_input" v-model="setForm.remarks" />

                                </el-form-item>
                                <el-form-item :label='$t("manage_set.remarks_ru")'>
                                    <el-input type="textarea" rows="4" class="qf_input" v-model="setForm.remarks_ru" />

                                </el-form-item>


        
                                <el-form-item :label='$t("manage_set.color")'>
                                    <div style="margin-top:8px;">
                                        <el-color-picker  v-model="setForm.color"   :predefine="predefineColors" />
                                    </div>
                                    
                                </el-form-item>
                    </el-form>
                </div>

            </div>

            <template #footer>
                <el-button type="default" @click="cancelEmpty(setRef)">{{$t("merak.cancel")}}</el-button>
                <el-button type="primary" plain v-if="editShow"
                    @click="saveContinue('2',setRef)">{{$t("merak.save_continue")}}</el-button>
                <el-button type="primary" @click="submitForm('1',setRef)">{{$t("merak.save")}}</el-button>

            </template>
        </el-drawer>

</div>























</template>

<script lang="ts" setup name="manageSet">
    import { Plus, Edit, Delete, EditPen } from '@element-plus/icons-vue';

    import { ref, reactive, onMounted, getCurrentInstance } from "vue";
    import serachBar from "@/components/SearchBar/index";
    import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
    import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
	import { getSetHeadApi, getSetListApi ,saveCreateSet ,saveEditSet ,delSet} from "@/api/modules/personalManagementApi/holiday";
    import I18n from "@/languages/index";


    import type { ElForm } from "element-plus";
    type FormInstance = InstanceType<typeof ElForm>;
    const setRef = ref < FormInstance > ();

    const { proxy } = getCurrentInstance();


    const tableRef = ref < MerakXTableInstance > ();

	const color = ref('rgba(255, 69, 0, 0.68)')
		const predefineColors = ref([
		'#E63415',
		'#FF6600',
		'#FFDE0A',
		'#1EC79D',
		'#14CCCC',
		'#4167F0',
		'#6222C9'
		
		])


    //批量操作
    const handleBatchClick = async (e) => {
        console.log(e)

    }


    //#region 搜索表单
    let search_val = ref("");
	//触发了快速搜索或者搜索方案
	const searchFn = params => {
	console.log(params)
	let postParams = { ...params.params,  search: params.search  };
	state.params = postParams;
	};

    //#endregion



    //#region 新增、编辑、删除
    const drawerTranslation = ref(false);
    const translationTitle = ref("新增假期");
    //表单参数结构
    const setForm = ref ({
		user_leaves_set_id:0,
        title: "",
        title_ru: "",
        remarks: "",
        remarks_ru: "",
        days: "",
		color:"#E63415"
    })
	const validateDay = (rule: any, value: any, callback: any) => {
        if (value === '') {
            callback(new Error(proxy.$t("main.requiredMsg")))
        } else {
			let reg = /^-?(0|([1-9][0-9]*))(\.[\d]+)?$/;
            if (reg.test(value)) {

            } else {
                callback(new Error("必须数字"))
            }
            callback()
        }
    };
    const translationRules = reactive({
        
		title: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		title_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		remarks: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		remarks_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		days: [{ required: true,validator: validateDay, trigger: "change" }],
       
    });


    
	const resetForm = (formEl: FormInstance | undefined) => {
	  if (!formEl) return
	  formEl.resetFields()
	}
    //新增操作
    const onPlus = () => {
        setForm.value = {
			user_leaves_set_id:0,
			title: "",
			title_ru: "",
			remarks: "",
			remarks_ru: "",
			days: "",
			color:"#E63415"
        }
		
		resetForm(setRef.value)
        //打开弹窗
        drawerTranslation.value = true;



    };
    //保存并继续
    const saveContinue = (typebtn: string, formEl: FormInstance | undefined) => {
        submitForm(typebtn, formEl)
    }

    const submitForm = async (typebtn: string, formEl: FormInstance | undefined) => {
        if (!formEl) return;
        await formEl.validate((valid, fields) => {
            if (valid) {
                //保存
                postAdd(typebtn, formEl);
                console.log("submit!");
            } else {
                console.log("error submit!", fields);
            }
        });
    };
    //新增  
    /**
     * typebtn 1保存 2保存并继续
    */
    const postAdd = (typebtn: string, formEl: FormInstance | undefined) => {
        if (editShow.value) {
            //新增
            saveCreateSet(setForm.value).then(res => {
                console.log(res)
                if (res.code == ResultEnum.SUCCESS) {
                    successMsg('保存成功!');
                    if (typebtn == 1) {
                        //关闭弹窗
                        drawerTranslation.value = false;
                        //formEl.resetFields();
                    } else {
                        let resetObj = {
							user_leaves_set_id:0,
                            title: "",
							title_ru: "",
							remarks: "",
							remarks_ru: "",
							days: "",
							color:"#E63415"
                          
                        }
                        setForm.value= { ...setForm.value, ...resetObj }
                      
					   resetForm(setRef.value)
                    }

                    tableRef.value?.reloadData();
                }else{
					failMsg(res.message);
				}
                
            }, err => {
                console.log(err)
            })

        } else {
            //编辑
            saveEditSet(setForm.value).then(res => {
                if (res.code == ResultEnum.SUCCESS) {
                    successMsg('编辑成功!');
                    //关闭弹窗
                    drawerTranslation.value = false;
                    // formEl.resetFields();
                    tableRef.value?.reloadData();
                }else {
                    failMsg(res.message);
                }
            }, err => {
                console.log(err)
            })
        }



    }

    //编辑
    let editShow = ref(true);
    const saveEdit = (row: setForm) => {
        
		const rowt = JSON.parse(JSON.stringify(row))
		setForm.value = rowt;
        //打开弹窗
        drawerTranslation.value = true;
        editShow.value = false;
    translationTitle.value="编辑假期";

    }

    //取消
    const cancelEmpty = (formEl: FormInstance | undefined) => {
        if (!formEl) return;
        formEl.resetFields();
        drawerTranslation.value = false;
    }



    //删除
    const delTranslation = (row: setForm) => {
        delConfimMsg({
            callback: val => {
                if (val == "confirm") {
                    delOne(row);
                }
            }
        });
    }

    const delOne = (row: setForm) => {
        delSet({ user_leaves_set_id: row.user_leaves_set_id }).then(res => {
            successMsg('删除成功!');
            setTimeout(() => {
                tableRef.value?.reloadData();
            }, 500)
        })
    }
    //#endregion

    const state = reactive < {
        params: Record < string, any>;
    columns: MerakXTableColumn[];
    } > ({
        params: {
            key_words: ""
        },
        columns: []
    });

    //权限01数据
    let authArr = ref({});

    const $t = I18n.global.t;

	const columnTypeAuth= reactive([]);





    if($t("lang")=='ru'){
        Object.assign(columnTypeAuth, [{type: 'handle', width: 280, slot: 'handler' }]);
    }else{
        Object.assign(columnTypeAuth,  [{type: 'handle', width: 120, slot: 'handler' }]);
    }





    //列表内容展示区
    const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
        const params: Record<string, any> = {};
			if (!!page) {
            Object.assign(params, { ...page }, from);
        }
        return await getSetListApi(params).then(res => {
            console.log(res)
            if (res.code == ResultEnum.SUCCESS) {
                let data = res.data;

				// 权限02
                authArr.value= res.auth_list;
             
              
				//表格中带有操作列
				if(!res.auth_list.edit.show){
			            console.log("不要操作列")
						columnTypeAuth.length=0;
						console.log(columnTypeAuth)
						
				}
				
                const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };

                return table_data;
            }
        })

    };



    //表头信息
    const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
        return await getSetHeadApi().then(res => {
            if (res.code == ResultEnum.SUCCESS) {
                let data = res.data as MerakXTableQuery.Columns;
                // const { pageSize, columns } = data as { pageSize: number; columns: MerakXTableColumn[] };
                 console.log(data.columns)

				for (let index = 0; index < data.columns.length; index++) {
					const element = data.columns[index];
					if(element.field=="color"){

					
						element["slots"]={ default: `color` }
					}
					
				}

                state.columns = data.columns;

                return data;
            }
        })
    };
</script>

<style  lang="scss">

.el-tag {
  border: none;
  aspect-ratio: 1;
}
    .translation {
        height: 100%;


    }


     .el-color-dropdown__btns .el-button{
        padding:5px 10px !important;
        min-width:20px;
    }

    // :deep(.el-color-dropdown) {
    //     .el-button {
    //        padding:5px 10px;
    //     }
    // }

        


  
	.merak_modal{
    .form-box{

        .el-form-item {
          
        }
    }
}
</style>